<template>
  <view class="container">
    <FilterNavbar resetToInit :title="title" :searchList="searchList" v-model:queryParam="queryParam" @confirm="to_loadData"></FilterNavbar>
    <view style="padding: 24rpx 24rpx 0" v-if="mode == 'platoon'">
      <view v-if="orderType == 'short-order' && orderInfo?.channelOrderMaintenance == 1" class="alert-info">
        <image class="info-img" src="@/static/images/alert_icon.png" mode="widthFix"></image>
        在企橙进行【修改车牌号】的操作，后续将不再以渠道平台订单的车辆进行更新。
      </view>
      <ve-card title="租赁信息" type="none" fold :initFold="false" style="margin-bottom: 0">
        <ve-cell label="预计租赁周期">
          <view>
            <view>{{ orderInfo.startTime + '-' + orderInfo.endTime || '-' }}</view>
            <view class="lease-time">租期：{{ orderInfo.rentDays || '-' }}</view>
          </view>
        </ve-cell>
        <ve-cell label="订单获取方式">{{ orderInfo.orderAcquisitionTypeName || '-' }}</ve-cell>
        <ve-cell label="车型">{{ orderInfo.modelName || '-' }}</ve-cell>
        <ve-cell label="订单来源" v-if="orderInfo.orderSourceName">{{ orderInfo.orderSourceName }}</ve-cell>
        <ve-cell label="车辆来源">{{ orderInfo.carSourceName }}</ve-cell>
      </ve-card>
    </view>
    <!-- 库存表 -->
    <ve-empty v-if="noSiteFlag" text="没有可用门店"></ve-empty>
    <CarSotckTable v-else selectable :platoonCarAble="false" ref="stockRef"></CarSotckTable>

    <!-- 二次确认 -->
    <ve-confirm titleText="提示" v-model="confirmVisible" @confirm="onUsedConfirm">
      <scroll-view scroll-y>
        <view class="confirmCont">
          <view v-for="(it, i) in resultMsg" :key="i">{{ it }}</view>
          <view>请确认是否{{ orderInfo.isEditLicenseNo ? '修改车牌号' : '排车' }}？</view>
        </view>
      </scroll-view>
    </ve-confirm>
    <ve-bottom-box>
      <ve-button size="long" type="primary" @click="onConfirm" :loading="confirmLoading">确认</ve-button>
    </ve-bottom-box>
    <!-- 铁行渠道自动维护订单拦截弹窗 -->
    <tiexing-order-intercept ref="tiexingOrderInterceptRef" />
  </view>
</template>

<script setup>
  // 选择车辆，并展示排车图
  // mode：选择车辆、排车（排车模式 有租赁信息，）（排车增加切换车辆来源 2024-04-01）
  import dayjs from 'dayjs'
  import { ref, computed, nextTick, provide } from 'vue'
  import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
  import tiexingOrderIntercept from '@/pages/order/short-order/components/order-item/modals/tiexing-order-intercept.vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import { platoonCarCheck, platoonCar, getSiteList, platoonCarLOrder } from '@/api/asset/car-stock'
  import { updateLongCarLicenseNo } from '@/api/order/lOrder'
  import { updateCarLicenseNo } from '@/api/order/sOrder'
  import CarSotckTable from './index'
  import useToast from '@/hooks/useToast'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
  import { orderIsTiexing } from '@/pages/order/short-order/tools'
  import { usePageDict } from '@/hooks/useDict'

  const dict = usePageDict('carStockDict')
  const tiexingOrderInterceptRef = ref()
  const searchList = computed(() => {
    return [
      {
        prop: 'carSource',
        label: '车辆来源',
        type: 'radio',
        attrs: {
          show: mode.value == 'platoon',
          options: [
            { value: 1, label: '门店车辆' },
            { value: 3, label: '跨门店调车' },
          ],
          change: (form, labelForm, searchList, val) => {
            orderInfo.value.carSource = val.value
            orderInfo.value.carSourceName = val.label
            // 本门店
            if (val.value == 1) {
              // 重置初始筛选值
              form.value.siteId = orderInfo.value.siteId
              labelForm.value.siteId = orderInfo.value.siteName
              // 修改其他筛选项请求参数
              searchList.value[1].attrs.disabled = true
              searchList.value[1].attrs.disabledValue = undefined
              searchList.value[2].attrs.params.siteId = orderInfo.value.siteId
              searchList.value[3].attrs.params.siteId = orderInfo.value.siteId
              searchList.value[4].attrs.params.siteId = orderInfo.value.siteId
            } else {
              // 跨门店
              searchList.value[1].attrs.disabledValue = orderInfo.value.siteId
              searchList.value[1].attrs.params.oldId = undefined
              searchList.value[1].attrs.disabled = false
              // 清空门店；其他关联参数不清空、会根据选择门店后清空
              form.value.siteId = undefined
              labelForm.value.siteId = undefined
            }
          },
        },
      },
      {
        prop: 'siteId',
        label: '门店',
        type: 'remote-select',
        attrs: {
          params: { oldId: queryParam.value.siteId },
          disabled: queryParam.value.carSource == 1,
          disabledValue: disabledSite,
          label: queryParam.value.siteName,
          type: 'site',
          required: true,
          change: (form, labelForm, searchList, val) => {
            form.value.seriesIdList = undefined
            form.value.modelIdList = undefined
            form.value.carIdList = undefined
            labelForm.value.seriesIdList = undefined
            labelForm.value.modelIdList = undefined
            labelForm.value.carIdList = undefined
            searchList.value[2].attrs.params = { siteId: val }
            searchList.value[3].attrs.params = { siteId: val }
            searchList.value[4].attrs.params = { siteId: val }
          },
        },
      },
      {
        prop: 'seriesIdList',
        label: '车系',
        type: 'remote-select',
        attrs: {
          type: 'carSeries_site',
          multiple: true,
          label: queryParam.value.seriesName,
          params: {
            siteId: queryParam.value.siteId,
          },
          change: (form, labelForm, searchList, val) => {
            form.value.modelIdList = undefined
            form.value.carIdList = undefined
            labelForm.value.modelIdList = undefined
            labelForm.value.carIdList = undefined
            searchList.value[3].attrs.params.seriesIdList = val
            searchList.value[4].attrs.params.seriesIdList = val
            searchList.value[4].attrs.params.modelIdList = undefined
          },
        },
      },
      {
        prop: 'modelIdList',
        label: '车型',
        type: 'remote-select',
        attrs: {
          type: 'multiple_carModel_site',
          multiple: true,
          label: queryParam.value.modelName,
          params: {
            siteId: queryParam.value.siteId,
            seriesIdList: queryParam.value.seriesIdList,
          },
          change: (form, labelForm, searchList, val) => {
            form.value.carIdList = undefined
            labelForm.value.carIdList = undefined
            searchList.value[4].attrs.params.modelIdList = val
          },
        },
      },
      {
        prop: 'carIdList',
        label: '车牌号',
        type: 'remote-select',
        attrs: {
          type: 'licenseNo',
          multiple: true,
          params: {
            siteId: queryParam.value.siteId,
            seriesIdList: queryParam.value.seriesIdList,
            modelIdList: queryParam.value.modelIdList,
          },
        },
      },
      {
        prop: 'dateRange',
        label: '时间',
        attrs: {
          label: queryParam.value.dateRange,
        },
        type: 'text',
      },
      {
        label: '订单渠道',
        prop: 'channelTypeList',
        type: 'remote-select',
        attrs: { multiple: true, title: '选择渠道', type: 'dict', outData: dict.channelTypeEnum },
      },
    ]
  })

  // 查询参数
  const queryParam = ref({
    siteId: undefined,
    seriesIdList: undefined,
    modelIdList: undefined,
    carIdList: undefined,
    type: undefined,
    startTime: '',
    endTime: '',
  })

  const confirmLoading = ref(false)
  const stockRef = ref([])
  const statistics = ref({})
  // 加载数据
  const to_loadData = (form, labelFrom) => {
    queryParam.value.siteName = labelFrom.siteId
    queryParam.value.seriesName = labelFrom.seriesIdList
    queryParam.value.modelName = labelFrom.modelIdList
    loadData()
  }
  const loadData = () => {
    nextTick(() => {
      const q_r = queryParam.value
      cacheQueryParam.value = { ...q_r }
      calcParamTime(q_r.startTime, q_r.endTime)
      stockRef.value.loadData(queryParam.value, (data) => {
        statistics.value = data
      })
    })
  }
  // 计算结束时间，最小1天时间, 最大100天
  const calcParamTime = (startTime, endTime) => {
    const start = dayjs(startTime).startOf('day')
    let end = dayjs(endTime).format('YYYY-MM-DD 23:59:59')
    queryParam.value.startTime = start.format('YYYY-MM-DD 00:00:00')
    const min = start.add(14, 'day').subtract(1, 'second')
    const max = start.add(100, 'day').subtract(1, 'second')
    if (min.isAfter(end)) {
      end = min.format('YYYY-MM-DD HH:mm:ss')
    }
    if (max.isBefore(end)) {
      end = max.format('YYYY-MM-DD HH:mm:ss')
    }
    queryParam.value.endTime = end
  }

  // 底部确认
  const confirmVisible = ref(false)
  const onConfirm = async () => {
    if (!carSelector.value.id) {
      uni.showToast({ icon: 'none', title: '请先选择车辆' })
      return
    }
    if (orderInfo.value.isEditLicenseNo && orderInfo.value.orderStatus == 300) {
      // 排车去排车
      if (mode.value == 'platoon') {
        platoonCarFn()
      } else {
        emitData()
      }
    } else {
      const errCount = await checkPlatoonCarFn()
      if (errCount) return
      // 排车去排车
      if (mode.value == 'platoon') {
        platoonCarFn()
      } else {
        emitData()
      }
    }
  }
  // 占用确认
  const onUsedConfirm = () => {
    if (mode.value == 'platoon') {
      platoonCarFn()
    } else {
      emitData()
    }
  }

  // 排车校验
  const resultMsg = ref([])
  const checkPlatoonCarFn = () => {
    let useType
    if (orderType.value == 'short-order') {
      useType = 2
    } else {
      useType = 3
    }
    const record = orderInfo.value
    const params = {
      refId: record.id,
      startTime: record.startTime,
      endTime: record.endTime,
      useType,
      carId: carSelector.value.id,
    }
    return new Promise((resolve) => {
      // 排车校验
      platoonCarCheck(params).then((res) => {
        const msgList = res.result.resultMsg || []
        if (msgList.length) {
          resultMsg.value = msgList
          confirmVisible.value = true
        }
        resolve(msgList.length)
      })
    })
  }
  // 确认操作
  const platoonCarFn = () => {
    if (orderInfo.value.isEditLicenseNo) {
      // 已还车/已完成的订单，修改车牌号不调用铁行接口，弹窗拦截进行提示
      if (orderIsTiexing(orderInfo.value) && [300, 1000].includes(orderInfo.value.orderStatus)) {
        confirmVisible.value = false
        return tiexingOrderInterceptRef.value.open(orderInfo.value, 'notCallTiexing', () => {
          updateCarLicenseNoFn()
        })
      }
      updateCarLicenseNoFn()
    } else {
      platoonCarOperateFn()
    }
  }
  // 修改车牌号操作
  const updateCarLicenseNoFn = () => {
    const record = orderInfo.value
    const params = {
      orderId: record.id,
      carId: carSelector.value.id,
      carSource: record.carSource,
      oldOrderCarId: record.oldOrderCarId,
    }
    confirmLoading.value = true
    let fetch = orderType.value == 'short-order' ? updateCarLicenseNo : updateLongCarLicenseNo
    fetch(params)
      .then((res) => {
        // 短租 待用车、用车中的订单，修改车牌号 调用铁行接口 false = 失败
        if (orderType.value == 'short-order' && [100, 200].includes(orderInfo.value.orderStatus) && res.result.success == false) {
          return tiexingOrderInterceptRef.value.open(
            { ...orderInfo.value, carLicenseNo: carSelector.value.value.licenseNo },
            'editShortOrderLicenseNo',
            () => {
              emitData()
              confirmLoading.value = false
            },
          )
        }
        useToast({
          title: res.result?.msg || res.message || '操作成功',
          icon: 'none',
        }).then(() => {
          emitData()
          confirmLoading.value = false
        })
      })
      .catch((error) => {
        useToast({
          title: error.data.message || '操作失败',
          icon: 'none',
        }).then(() => {
          confirmLoading.value = false
        })
      })
      .finally(() => {
        confirmVisible.value = false
      })
  }
  // 排车(长租、短租)
  const platoonCarOperateFn = () => {
    const record = orderInfo.value
    const params = {
      id: record.id,
      carId: carSelector.value.id,
      carSource: record.carSource,
      type: platoonType,
    }
    let fetch = platoonCarLOrder
    if (orderType.value == 'short-order') {
      fetch = platoonCar
    }
    fetch(params)
      .then(({ result }) => {
        // 待用车的订单 调用铁行的接口 false = 失败，弹出警告弹窗 platoonType = 2 改排
        if (platoonType == 2 && orderInfo.value.orderStatus == 100 && result && result.success == false) {
          return tiexingOrderInterceptRef.value.open(
            { ...orderInfo.value, carLicenseNo: carSelector.value.value.licenseNo },
            'editShortOrderReschedule',
            () => {
              emitData()
            },
          )
        }
        useToast({
          title: platoonType == 1 ? '排车成功' : '改排成功',
        }).then(() => {
          emitData()
        })
      })
      .finally(() => {
        confirmVisible.value = false
      })
  }

  // 提交数据
  const emitData = () => {
    const car_s = carSelector.value
    if (orderInfo.value.carId != car_s.id) {
      uni.$emit('carStock:selectCarOk', car_s.id, car_s.value, {
        // 记录门店id、车系、车型
        siteId: cacheQueryParam.value.siteId,
        seriesIdList: cacheQueryParam.value.seriesIdList,
        modelIdList: cacheQueryParam.value.modelIdList,
      })
    }
    useLoadDataAndHotUpdateNavigateBack()
  }

  // 车辆选择器
  const carSelector = ref({
    id: 1,
    record: null,
    c_id: 1, // 排车的车辆id
  })
  provide('carSelector', carSelector)
  const orderInfo = ref({})
  // mode模式：select、platoon
  const mode = ref('select')
  const cacheQueryParam = ref()
  const title = ref('选择车牌号')
  let disabledSite
  const noSiteFlag = ref(false)
  const orderType = ref('short-order')
  // 排车类型:1排车 2改排
  let platoonType = 1
  // 接收参数
  let page_options
  onLoad((options) => {
    const { data_json, orderInfo_json, mode: mode_v = 'select', type } = options || {}
    // 缓存数据
    page_options = {
      data: JSON.parse(data_json || '{}'),
      orderInfo: JSON.parse(orderInfo_json || '{}'),
    }

    const data = page_options.data
    // 初始化订单信息
    orderInfo.value = page_options.orderInfo
    console.log(data, 'orderInfo.value')
    // 初始化搜索参数
    queryParam.value = {
      startTime: data.startTime,
      endTime: data.endTime,
      dateRange: dayjs(data.startTime).format('YYYY-MM-DD') + ' 至 ' + dayjs(data.endTime).format('YYYY-MM-DD'),
      rentDays: data.rentDays,
      // 搜索框会修改
      siteId: data.siteId,
      siteName: data.siteName,
      seriesIdList: data.seriesIdList,
      seriesName: data.seriesName,
      modelIdList: data.modelIdList ? data.modelIdList : data.modelId ? [+data.modelId] : undefined,
      modelName: data.modelName,
      carSource: data.carSource,
      orderSourceName: data.orderSourceName,
    }
    // 清空carId，防止选择车辆后，再次进入仅展示当前选中车辆
    queryParam.value.carId = undefined
    mode.value = mode_v
    // 订单类型
    orderType.value = type

    // 初始化选择车辆
    carSelector.value = {
      id: orderInfo.value.carId,
      value: {},
      c_id: data.platoonCarId, // 排车的车辆id
    }
    if (mode_v == 'platoon') {
      carSelector.value.c_id = data.platoonCarId
      title.value = '排车'
      if (data.platoonCarId) {
        // 初始化改排的选中车辆
        carSelector.value.id = undefined
        title.value = '改排'
        platoonType = 2
      }
      if (orderInfo.value.isEditLicenseNo) {
        title.value = '修改车牌号'
      }
    }
    // 初始化门店
    initSite()
  })

  const initSite = () => {
    const { data, orderInfo } = page_options || {}
    // 跨门店订单
    disabledSite = ''
    if (data.carSource == 3) {
      // 跨门店清除车系车型,防止other门店没有这个车型
      queryParam.value.seriesIdList = undefined
      queryParam.value.seriesName = undefined
      queryParam.value.modelIdList = undefined
      queryParam.value.modelName = undefined
      disabledSite = orderInfo.siteId
      // 防止重复赋值；跨门店用车有siteId时不需要初始化门店
      if (disabledSite != queryParam.value.siteId) {
        loadData()
        return
      }
      // 可用门店
      getSiteList({ siteStatusList: ['10'] }).then((res) => {
        if (res.code == 200) {
          const siteList = res.result
          if (siteList.length <= 1) {
            noSiteFlag.value = true
            return
          }
          const site = siteList.find((it) => it.id != disabledSite)
          if (site) {
            queryParam.value.siteId = site.id
            queryParam.value.siteName = site.siteName
            loadData()
          } else {
            noSiteFlag.value = true
          }
        }
      })
    } else {
      loadData()
    }
  }

  onPullDownRefresh(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .container {
    height: auto;
    min-height: 100%;
  }
  .alert-info {
    padding: 24rpx;
    background-color: #e8f3ff;
    font-size: 14px;
    margin-bottom: 16rpx;

    .info-img {
      width: 16px;
      margin-top: -4px;
    }
  }
  .confirmCont {
    max-height: 60vh;
  }
  .lease-time {
    color: #3072f6;
  }
</style>
